# Maintainer: Jan Alexander Steffens (heftig) <heftig@archlinux.org>

pkgbase=linux
pkgver=git
pkgrel=1
pkgdesc='Linux'
_srctag=v${pkgver%.*}-${pkgver##*.}
url="https://git.archlinux.org/linux.git/log/?h=$_srctag"
arch=('arm64' 'x86_64')
license=(GPL2)
makedepends=(
  bc kmod libelf pahole
  #  xmlto python-sphinx python-sphinx_rtd_theme graphviz imagemagick
  git
)
options=('!strip')
_srcname=archlinux-linux
source=(
  "$_srcname::https://git.archlinux.org/linux.git"
)
validpgpkeys=(
  'ABAF11C65A2970B130ABE3C479BE3E4300411886'  # Linus Torvalds
  '647F28654894E3BD457199BE38DBBDC86092693E'  # Greg Kroah-Hartman
  'A2FF3A36AAA56654109064AB19802F8B0D70FC30'  # Jan Alexander Steffens (heftig)
)
sha256sums=('SKIP' 'SKIP')

export KBUILD_BUILD_HOST=archlinux
export KBUILD_BUILD_USER=$pkgbase
export KBUILD_BUILD_TIMESTAMP="$(date -Ru${SOURCE_DATE_EPOCH:+d @$SOURCE_DATE_EPOCH})"

create_config() {
  local autoconfig="${CONFIG_FILE##*/}"
  case $autoconfig in
    randconfig*)
      make randconfig
      ;;
    *config)
      make $autoconfig
      ;;
  esac
}

prepare() {
  echo "build_stage: 10"  # Prepare phase started

  if command -v yum >/dev/null; then
    echo "skip texlive python-sphinx install"
    yum install -y make gcc fakeroot bison flex openssl-devel dwarves elfutils-libelf-devel
  elif command -v dnf >/dev/null; then
    dnf install -y texlive python-sphinx
  elif command -v apt-get >/dev/null; then
    apt-get install -y apt install make gcc fakeroot bison flex libssl-dev dwarves libelf-dev
  elif command -v apt >/dev/null; then
    apt install -y apt install make gcc fakeroot bison flex libssl-dev dwarves libelf-dev
  elif command -v pacman >/dev/null; then
    pacman -Sy --noconfirm texinfo python-sphinx
  fi

  cd $_srcname

  echo "build_stage: 11"  # Setting version and applying patches
  echo "Setting version..."
  echo "-$pkgrel" > localversion.10-pkgrel
  echo "${pkgbase#linux}" > localversion.20-pkgname

  # applying the patchset
  echo "Applying patches..."
  if [ -n "$PATCHSET_PATH" ]; then
    for patch in $PATCHSET_PATH/*.patch; do
      patch -p1 < "$patch"
    done
  fi

  echo "build_stage: 12"  # Setting kernel config
  echo "Setting config..."

  # 获取配置名称（支持 config 和 autoconfig）
  local config_name="${config:-${autoconfig}}"

  # Handle randconfig with unified download-generate-upload loop (inspired by 440.diff)
  # Only apply this logic for autoconfig: randconfig, not config: randconfig (to avoid affecting old data)
  if [[ -n "$autoconfig" && "$autoconfig" =~ ^randconfig ]]; then
    . "$LKP_SRC/lib/http.sh"
    . "$LKP_SRC/lib/upload.sh"

    # Ensure http_client_cmd is exported (workaround for lib/curl.sh not exporting it)
    [ -n "$http_client_cmd" ] && export http_client_cmd

    echo "Handling randconfig: $config_name"

    local remote_config_path="ss/config/$pkgbase/$config_name"
    local config_url="$initrd_http_prefix$file_store_root/$remote_config_path"


    # First, try to download from server (maybe it already exists as a fixed config)
    echo "[$(date '+%T')] Attempting to download randconfig from server..."
    if http_get_file "$config_url" "$CONFIG_FILE" 2>/dev/null && [ -s "$CONFIG_FILE" ]; then
      echo "[$(date '+%T')] Successfully downloaded existing config from server"
      cp "$CONFIG_FILE" .config
    else
      # Config doesn't exist on server, need to generate and upload
      echo "[$(date '+%T')] Config not found on server, will generate new randconfig"

      local max_retries=3
      local retry_count=0

      while [ $retry_count -lt $max_retries ]; do
        echo "[$(date '+%T')] Generate-upload attempt $((retry_count + 1))/$max_retries"

        # Step 1: Generate new config
        echo "[$(date '+%T')] Generating new randconfig..."
        create_config
        cp .config "$CONFIG_FILE"

        # Step 2: Check before upload (race detection - from 440.diff)
        echo "[$(date '+%T')] Checking if another job uploaded while we generated..."
        if http_get_file "$config_url" "/dev/null" 2>/dev/null; then
          echo "[$(date '+%T')] Race condition: another job uploaded, downloading their config..."
          if http_get_file "$config_url" "$CONFIG_FILE" 2>/dev/null && [ -s "$CONFIG_FILE" ]; then
            echo "[$(date '+%T')] Successfully downloaded from racing job"
            cp "$CONFIG_FILE" .config
            break
          else
            echo "[$(date '+%T')] Download failed, retrying generation..."
            rm -f "$CONFIG_FILE"
            retry_count=$((retry_count + 1))
            sleep 5
            continue
          fi
        fi

        # Step 3: Upload our generated config
        echo "[$(date '+%T')] Uploading newly generated randconfig..."
        if upload_one_srv "$CONFIG_FILE" "$file_store_root/$remote_config_path"; then
          echo "[$(date '+%T')] Successfully uploaded randconfig"
          break
        fi

        echo "[$(date '+%T')] Upload failed, retrying..."
        rm -f "$CONFIG_FILE"
        retry_count=$((retry_count + 1))
        sleep 5
      done

      # Final check
      if [ ! -s "$CONFIG_FILE" ] || [ ! -f .config ]; then
        echo "ERROR: Failed to obtain randconfig after $max_retries retries" >&2
        exit 1
      fi
    fi
  elif [ -s "$CONFIG_FILE" ]; then
    cp "$CONFIG_FILE" .config
  elif [ -n "$CONFIG_FILE" ]; then
    create_config
    cp .config "$CONFIG_FILE"
  else
    echo "make defconfig..."
    make defconfig
    sed -i 's/# CONFIG_MODULES is not set/CONFIG_MODULES=y/g' .config
  fi

  echo "build_stage: 13"  # Running olddefconfig
  make olddefconfig -j8
  if [ "$pkgbase" == 'linux' ]; then
    cp .config "$linux_CGZDEST/kconfig"
  elif [ -n "$CONFIG_FILE" ]; then
    cp .config "$CONFIG_FILE"
  elif [ -n "$cci_dir" ]; then
    mkdir -p $cci_dir/$pkgbase/$config
    cp .config $cci_dir/$pkgbase/$config
  fi

  if ! $(make -s kernelrelease > version); then
    cat version
    exit 1
  fi

  echo "build_stage: 14"  # Prepare phase completed
  echo "Prepared $pkgbase version $(<version)"
}

build() {
  cd $_srcname
  echo "build_stage: 20"  # Build phase started - kernel compilation
  if [ -n "$PROFILE_GCOV_DIR" ]; then
    make all -j8 KCFLAGS="-fprofile-use -fprofile-correction -Wno-error=coverage-mismatch -fprofile-dir=$PROFILE_GCOV_DIR"
  elif [ -n "$make_args" ]; then
    make all $make_args
  else
    make all -j8
  fi
  echo "build_stage: 29"  # Build phase completed
  #  make htmldocs -j8 || true
}

_package-modules() {
  echo "build_stage: 30"  # Package phase started - modules
  pkgdesc="The $pkgdesc kernel and modules"
  depends=(coreutils kmod initramfs)
  optdepends=('crda: to set the correct wireless channels of your country'
              'linux-firmware: firmware images needed for some devices')
  provides=(VIRTUALBOX-GUEST-MODULES WIREGUARD-MODULE)
  replaces=(virtualbox-guest-modules-arch wireguard-arch)

  cd "${srcdir}/$_srcname"
  local kernver="$(<version)"
  local modulesdir="$pkgdir/lib/modules/$kernver"

  echo "Installing boot image..."
  # systemd expects to find the kernel here to allow hibernation
  # https://github.com/systemd/systemd/commit/edda44605f06a41fb86b7ab8128dcf99161d2344
  #install -Dm644 "$(make -s image_name)" "$modulesdir/vmlinuz"

  # lkp feature
  install -Dm644 "$(make -s image_name)" "$linux_CGZDEST/vmlinuz"

  # Used by mkinitcpio to name the kernel
  echo "$pkgbase" | install -Dm644 /dev/stdin "$modulesdir/pkgbase"

  echo "Installing modules..."
  make INSTALL_MOD_PATH="$pkgdir" INSTALL_MOD_STRIP=1 modules_install

  # remove build and source links
  rm -f "$modulesdir"/{source,build}
}

_package-headers() {
  echo "build_stage: 35"  # Package phase - headers
  pkgdesc="Headers and scripts for building modules for the $pkgdesc kernel"

  cd "${srcdir}/$_srcname"
  local builddir="$pkgdir/usr/lib/modules/$(<version)/build"

  echo "Installing build files..."
  if [ "$pkgbase" == 'linux' ]; then
    cp System.map "$linux_CGZDEST/System.map"
  elif [ -n "$cci_dir" ]; then
    mkdir -p $cci_dir/$pkgbase/$config
    cp System.map $cci_dir/$pkgbase/$config
  fi
  install -Dt "$builddir" -m644 .config Makefile Module.symvers System.map \
    localversion.* version vmlinux
  install -Dt "$builddir/kernel" -m644 kernel/Makefile
  case "$CARCH" in
    x86_64)
        install -Dt "$builddir/arch/x86" -m644 arch/x86/Makefile
        ;;
    aarch64)
        install -Dt "$builddir/arch/arm64" -m644 arch/arm64/Makefile
        ;;
  esac
  cp -t "$builddir" -a scripts

  # add objtool for external module building and enabled VALIDATION_STACK option
  #install -Dt "$builddir/tools/objtool" tools/objtool/objtool

  # add xfs and shmem for aufs building
  mkdir -p "$builddir"/{fs/xfs,mm}

  echo "Installing headers..."
  cp -t "$builddir" -a include
  case $CARCH in
    x86_64)
        cp -t "$builddir/arch/x86" -a arch/x86/include
        install -Dt "$builddir/arch/x86/kernel" -m644 arch/x86/kernel/asm-offsets.s
        ;;
    aarch64)
        cp -t "$builddir/arch/arm64" -a arch/arm64/include
        install -Dt "$builddir/arch/arm64/kernel" -m644 arch/arm64/kernel/asm-offsets.s
        ;;
    *)
        cp -t "$builddir/arch/$CARCH" -a arch/arm64/include
        install -Dt "$builddir/arch/$CARCH/kernel" -m644 arch/$CARCH/kernel/asm-offsets.s
        ;;
  esac

  install -Dt "$builddir/drivers/md" -m644 drivers/md/*.h
  install -Dt "$builddir/net/mac80211" -m644 net/mac80211/*.h

  # http://bugs.archlinux.org/task/13146
  install -Dt "$builddir/drivers/media/i2c" -m644 drivers/media/i2c/msp3400-driver.h

  # http://bugs.archlinux.org/task/20402
  install -Dt "$builddir/drivers/media/usb/dvb-usb" -m644 drivers/media/usb/dvb-usb/*.h
  install -Dt "$builddir/drivers/media/dvb-frontends" -m644 drivers/media/dvb-frontends/*.h
  install -Dt "$builddir/drivers/media/tuners" -m644 drivers/media/tuners/*.h

  echo "Installing KConfig files..."
  find . -name 'Kconfig*' -exec install -Dm644 {} "$builddir/{}" \;

  echo "Removing unneeded architectures..."
  local arch
  local keep_arch

  case "$CARCH" in
      x86_64)
          keep_arch="x86"
          ;;
      aarch64)
          keep_arch="arm64"
          ;;
      *)
          keep_arch="$CARCH"
          ;;
  esac
  for arch in "$builddir"/arch/*/; do
    dir_name=$(basename "$arch")

    if [[ "$dir_name" == "$keep_arch" ]]; then
        continue
    fi

    echo "Removing $dir_name"
    rm -r "$arch"
  done

  echo "Removing documentation..."
  rm -r "$builddir/Documentation"

  echo "Removing broken symlinks..."
  find -L "$builddir" -type l -printf 'Removing %P\n' -delete

  echo "Removing loose objects..."
  find "$builddir" -type f -name '*.o' -printf 'Removing %P\n' -delete

  echo "Stripping build tools..."
  local file
  while read -rd '' file; do
    case "$(file -bi "$file")" in
      application/x-sharedlib\;*)      # Libraries (.so)
        strip -v $STRIP_SHARED "$file" ;;
      application/x-archive\;*)        # Libraries (.a)
        strip -v $STRIP_STATIC "$file" ;;
      application/x-executable\;*)     # Binaries
        strip -v $STRIP_BINARIES "$file" ;;
      application/x-pie-executable\;*) # Relocatable binaries
        strip -v $STRIP_SHARED "$file" ;;
    esac
  done < <(find "$builddir" -type f -perm -u+x ! -name vmlinux -print0)

  echo "Stripping vmlinux..."
  strip -v $STRIP_STATIC "$builddir/vmlinux"

  echo "Adding symlink..."
  mkdir -p "$pkgdir/usr/src"
  ln -sr "$builddir" "$pkgdir/usr/src/$pkgbase"
}

_package-docs() {
  pkgdesc="Documentation for the $pkgdesc kernel"

  cd "${srcdir}/$_srcname"
  local builddir="$pkgdir/usr/lib/modules/$(<version)/build"

  echo "Installing documentation..."
  local src dst
  while read -rd '' src; do
    dst="${src#Documentation/}"
    dst="$builddir/Documentation/${dst#output/}"
    install -Dm644 "$src" "$dst"
  done < <(find Documentation -name '.*' -prune -o ! -type d -print0)

  echo "Adding symlink..."
  mkdir -p "$pkgdir/usr/share/doc"
  ln -sr "$builddir/Documentation" "$pkgdir/usr/share/doc/$pkgbase"
}

#  pkgname=("$pkgbase")

#  package() {
  #  _package
  #  _package-headers
  #  _package-docs
#  }

pkgname=(
  "$pkgbase-modules"
  "$pkgbase-headers"
  #  "$pkgbase-docs"
)
for _p in "${pkgname[@]}"; do
eval "package_$_p() {
  $(declare -f "_package${_p#$pkgbase}")
  _package${_p#$pkgbase}
}"
done

# vim:set ts=8 sts=2 sw=2 et:
